import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper objectMappe = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应格式
        resp.setContentType("application/json; charset=utf8");
        req.setCharacterEncoding("utf8");
        //1.从响应中获取blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null) {//博客列表页
            getBlogListUser(req, resp);
        } else {//博客详情页
            getBlogUser(req, resp, Integer.parseInt(blogId));
        }
    }
    //博客详情页
    private void getBlogUser(HttpServletRequest req, HttpServletResponse resp, int blogId) throws IOException {
        //1.根据blogId从数据库中取出Blog
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlog(blogId);
        if(blog == null) {
            resp.setStatus(403);
            resp.getWriter().write("blogId有误!");
            return;
        }
        //2.根据blog，取出userId
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if(user == null) {
            resp.setStatus(403);
            resp.getWriter().write("userId有误!");
            return;
        }
        //3.返回响应
        resp.getWriter().write(objectMappe.writeValueAsString(user));
    }
    //博客列表页
    private void getBlogListUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.获取session会话
        HttpSession session = req.getSession();
        if(session == null) {
            resp.sendRedirect("login.html");
            return;
        }
        //2.从会话中获取user对象
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.sendRedirect("login.html");
            return;
        }
        //3.设置响应
        resp.getWriter().write(objectMappe.writeValueAsString(user));
    }
}
